[contents] [prev] [top] (17 out of 17)

Compound Expressions and Variable Scope

Compound expressions define a new local variable scope for the expressions within them. Local variables declared in the block are only available to the expressions within that block that occur after the declaration.

global z, x := 15
( 
	local q:= 10
	z := x + q
)
z -- evaluate z
25
q-- evaluate q
-- ** Warning: Undeclared global q

Note that z continued to exist outside the block because it was declared globally. The variable q, however, was declared locally, and so is only available within the block expression in which it was defined. In the example that follows, note that the local definition within the block overrides the global definition outside the block.

global var1 := "string"
(
	local var1 := "a different string"
	var1 		-- the block returns the value of this because it's
	 	 	-- the last expression in the block
)
"a different string"
var1
"string"
The first var1 evaluates to the value of the local assignment, as declared in the block. The second var1 , which occurs after the end of the block, returns the value of the global var1 variable.

When ScriptX encounters a variable reference, it first checks the local scope for the value of that variable, and then each surrounding variable scope. This causes local variables to "hide" the values of global variables and local variables of the same name, including variables that may contain substrate classes, objects, and functions.

The following example shows that the global variable is visible inside the block until it is overriden by a local variable with the same name. After the block's scope has ended, the local variable no longer exists.

global a, b:2, c:3
(
	a := b
	local b:5
	c := b
)
5
a -- evaluate a
2
b -- evaluate b
2
c -- evaluate c
5


This document is part of the ScriptX Language Guide, one of the volumes of the ScriptX Technical Reference Series. ScriptX is developed by the ScriptX Engineering Team at Apple Computer, successor to the Kaleida Engineering Team at Kaleida Labs, Inc.

Copyright 1996 Apple Computer, Inc. All Rights Reserved.